<template>
  <div class="add-version-container">
    <el-dialog title="设计信息"
               :visible.sync="dialogVisible"
               width="50%"
               :before-close="handleClose">
      <el-row :gutter="20">
        <el-form ref="requestParam"
                 :model="requestParam"
                 :rules="rules"
                 label-width="160px">
          <el-col :span="24">
            <el-form-item label="是否采用装配式装修"
                          prop="is_assembly">
              <el-radio-group v-model="requestParam.is_assembly">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否全装修"
                          prop="is_full_trim">
              <el-radio-group v-model="requestParam.is_full_trim">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="全装修面积㎡"
                          prop="full_trim_area">
              <el-input v-model="requestParam.full_trim_area"
                        placeholder="请输入全装修面积㎡"></el-input>
            </el-form-item>
            <el-form-item label="建筑面积㎡"
                          prop="building_area">
              <el-input v-model="requestParam.building_area"
                        placeholder="请输入建筑面积㎡"></el-input>
            </el-form-item>
            <el-form-item label="地上建筑面积㎡"
                          prop="ground_building_area">
              <el-input v-model="requestParam.ground_building_area"
                        placeholder="请输入地上建筑面积㎡"></el-input>
            </el-form-item>
            <el-form-item label="地下建筑面积㎡"
                          prop="underground_building_are">
              <el-input v-model="requestParam.underground_building_area"
                        placeholder="请输入地下建筑面积㎡"></el-input>
            </el-form-item>
            <el-form-item label="建筑层数"
                          prop="building_floors">
              <el-input v-model="requestParam.building_floors"
                        placeholder="请输入建筑层数"></el-input>
            </el-form-item>
            <el-form-item label="地上层数"
                          prop="ground_floors">
              <el-input v-model="requestParam.ground_floors"
                        placeholder="请输入地上层数"></el-input>
            </el-form-item>
            <el-form-item label="地下层数"
                          prop="underground_floors">
              <el-input v-model="requestParam.underground_floors"
                        placeholder="请输入地下层数"></el-input>
            </el-form-item>
            <el-form-item label="建筑类型">
              <el-select v-model="requestParam.building_type"
                         class="common-style"
                         placeholder="选择建筑类型">
                <el-option v-for="item in buildingTypeList"
                           :key="item.value"
                           :label="item.name"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="结构类型"
                          prop="struct_type">
              <el-select v-model="requestParam.struct_type"
                         class="common-style"
                         placeholder="请选择">
                <el-option v-for="item in structTypeArr"
                           :key="item.value"
                           :label="item.name"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="装配率%"
                          prop="assembly_rate	">
              <el-input v-model="requestParam.assembly_rate	"
                        placeholder="请输入装配率%"></el-input>
            </el-form-item>
            <el-form-item label="装配率计算书"
                          prop="assembly_rate_cal_file_name">
              <el-upload class="upload-demo"
                         action
                         :multiple="true"
                         ref="uploadFile"
                         :auto-upload="false"
                         :http-request="uploadFile"
                         :on-preview="handlePreview"
                         :on-remove="handleRemove"
                         :on-change="handleFileChange"
                         :before-remove="beforeRemove"
                         :limit="limitNum"
                         :show-file-list="false"
                         :on-exceed="handleExceed"
                         :file-list="fileList">
                <el-button size="small"
                           type="primary">点击上传</el-button>
                <!-- <div slot="tip"
                     class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
              <ul class="ul-style">
                <li v-for="(item,i) in uploadDraweArr"
                    :key="i">
                  <p>{{item.name}}</p>
                  <p>
                    <el-button type="text"
                               :disabled="$route.query.type=='detail'?true:false"
                               @click="onDelPaper(item,i)">x</el-button>
                  </p>
                </li>
              </ul>
            </el-form-item>
          </el-col>
          <el-col :span="24"
                  class="bottom-box">
            <el-button @click="onCancel">取消</el-button>
            <el-button type="primary"
                       @click="onSure('requestParam')">确定</el-button>
          </el-col>
        </el-form>
      </el-row>
      <!-- 上传的个数 -->
      <el-dialog :title="'正在上传(' + uploadFileIndex + '/' + uploadQuene.length + ')'"
                 :modal="mode === 'edit'"
                 width="70%"
                 @close="uploadDialogClose"
                 :modal-append-to-body="false"
                 :append-to-body="true"
                 :visible.sync="uploadQueneDialogVisible">
        <ul class="upload-quene-list">
          <li class="upload-quene-item"
              v-for="(item, index) in uploadQuene"
              :key="index">
            <span class="file-name">
              <img src="@/assets/file-icon.png"
                   alt="" />
              <i>{{ item.name }}</i>
            </span>
            <span class="file-size">{{ item.file_size }}</span>
            <!-- <span class="dir-name">{{ choosedTreeNode.dir_name }}</span> -->
            <span v-if="item.status !== 'resolve'"
                  class="staus">{{
            item.percent
          }}</span>
            <span class="status"
                  v-if="item.status === 'resolve'">
              <i class="fa fa-check-circle"></i>
            </span>
          </li>
        </ul>
        <div slot="footer"
             class="dialog-footer">
          <el-button @click="closeDialog"
                     type="primary">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import OSS from 'ali-oss';
import { standardCodeApi } from '@/services/StandardCode'
import { projectDecomApi, ProDesignDecomApi } from '@/services/ProjectCenter'
export default {
  props: {//传参
    objRow: {
      type: Object,
      default: () => {
        return {}
      }
    },
    designInfoVisible: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data () {
    return {
      buildingTypeList: [],
      nodeCount: 0,
      timerId: 0,
      mode: 'edit',//编辑
      limitNum: 1,//默认上传的个数最大为1
      uploadDraweArr: [],//已上传的图纸
      uploadQueneDialogVisible: false,
      // 等待上传文件列表
      uploadQuene: [],
      // 当前上传文件在列表中的index
      uploadFileIndex: 0,
      fileList: [],//上传的文件
      structTypeArr: [],//结构类型
      dialogVisible: false,
      requestParam: {
        building_area: '',
        underground_building_area: '',
        building_floors: '',
        ground_floors: '',
        underground_floors: '',
        ground_building_area: '',
        building_type: '',
        resolve_wbs_design_id: '',
        resolve_wbs_id: '',
        is_assembly: '',
        is_full_trim: '',
        assembly_rate: '',
        struct_type: '',
        full_trim_area: '',
        assembly_rate_cal_file_name: '',
        assembly_rate_cal_file: '',
      },
      rules: {
        //   assembly_rate_cal_file_name: [
        //     { required: true, message: '装配率计算书不能为空', trigger: ['blur', 'change'] }
        //   ],
        //   is_assembly: [
        //     { required: true, message: '是否采用装配式装修不能为空', trigger: ['blur', 'change'] }
        //   ],
        //   full_trim_area: [
        //     { required: true, message: '全装修面积不能为空', trigger: ['blur', 'change'] }
        //   ],
        //   is_full_trim: [
        //     { required: true, message: '是否全装修不能为空', trigger: ['blur', 'change'] }
        //   ],
        //   assembly_rate: [
        //     { required: true, message: '装配率%不能为空', trigger: ['blur', 'change'] }
        //   ]
      }
    }
  },
  methods: {
    // 获取建筑类型标准码
    getBuildingTypeCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'rosolveBuildingType'
        }
      }).then(res => {
        if (res.code === 0 && res.data.list) {
          this.buildingTypeList = res.data.list
        }
      }, err => {
        console.log(err)
      })
    },
    onDelPaper (file, i) {//删除当前的图纸
      this.$confirm(`确定移除 ${file.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.requestParam.assembly_rate_cal_file_name = '';
        this.requestParam.assembly_rate_cal_file = '';
        this.uploadDraweArr.splice(i, 1);
        this.$message.success('删除成功!');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 关闭上传文件弹框,清空队列,调用文件列表新增接口
    closeDialog () {
      this.uploadDraweArr = [];
      this.requestParam.assembly_rate_cal_file_name = '';
      this.requestParam.assembly_rate_cal_file = '';
      let newUploadLength = this.uploadQuene.length;
      let oldUploadLength = this.uploadDraweArr.length;
      let allLength = newUploadLength + oldUploadLength;
      if (allLength > 1) {//个数不能超过最大限制5
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${newUploadLength} 个文件，共选择了 ${allLength} 个文件`);
      } else {//个数不超过限制时执行
        if (this.uploadQuene.length > 0) {
          this.uploadQuene.map((item, ind, arr) => {
            this.requestParam.assembly_rate_cal_file_name = item.name;
            this.requestParam.assembly_rate_cal_file = item.file_address;
            this.uploadDraweArr.push(item)
          })
        };

      }

      // this.uploadDraweArr;//连接为一个数组
      // this.uploadFileIndex = 0;
      // this.uploadQuene = []
      // this.createProjectFile()
      // this.$refs.uploadFile.clearFiles();//重置
      this.uploadQueneDialogVisible = false
    },
    handleFileChange (file, filelist) {
      // if (this.choosedTreeNode.p_project_dir_id) {
      // 简易版debounce，以最后一次为准
      clearTimeout(this.timerId);//清空延时器
      this.timerId = setTimeout(() => {
        // elementui 上传组件会把filelist中所有status为ready的数据上传，
        // 因此首先把所有数据的status置为waiting，然后依次把status置为ready，实现队列效果
        filelist.map(item => {
          item.file_alias = item.name
          item.file_ext = item.name.split('.')[1]
          item.file_size = (item.size / (1024 * 1024)).toFixed(2) + 'M'
          item.status = 'waiting'
          this.$set(item, 'percent', '0%')
        })
        this.uploadQuene = filelist
        this.uploadFileIndex = 0
        this.uploadQueneDialogVisible = true
        // 控制文件一个个上传
        this.uploadFileQuene()
      }, 300)
      // } else {
      //   this.$message.warning('请选择文件夹')
      // }
    },
    // 点击右上角的×关闭时，只清空队列，不调用新增
    uploadDialogClose () {
      this.uploadFileIndex = 0;
      this.uploadQuene = [];//清空
      this.$refs.uploadFile.clearFiles();//重置
      this.uploadQueneDialogVisible = false
    },
    uploadFile (file) {
      // 上传文件
      var client = new OSS({
        region: 'oss-cn-hangzhou',
        accessKeyId: this.util.decrypt(process.env.AES_OSS_ID),
        accessKeySecret: this.util.decrypt(process.env.AES_OSS_SECRET),
        bucket: process.env.bucket
      })
      let address = 'platform/projectDecome/editDesignInfo/' + file.file.name
      client
        .multipartUpload(address, file.file, {
          progress: percent => {
            // this.$set(this.uploadQuene[this.uploadFileIndex], 'percent', parseInt(percent * 100) + '%')
            this.uploadQuene[this.uploadFileIndex].percent =
              parseInt(percent * 100) + '%'
          }
        })
        .then(res => {
          // data.attach = 'http://dev-consult-new.oss-cn-hangzhou.aliyuncs.com/' + res.name
          this.uploadQuene[this.uploadFileIndex].status = 'resolve'
          this.uploadQuene[this.uploadFileIndex].file_address = res.res.requestUrls[0].split('?')[0]
          this.uploadFileIndex++
          this.uploadFileQuene();//队列
          // this.fileList = this.uploadQuene
        })
    },// 通过队列的方式上传
    uploadFileQuene () {
      if (this.uploadFileIndex < this.uploadQuene.length) {
        this.uploadQuene[this.uploadFileIndex].status = 'ready'
        this.$refs.uploadFile.submit();
      }
    },
    getDesignInfo () {//设计信息
      ProDesignDecomApi.getDesignInfo({
        params: {
          resolve_wbs_id: this.objRow.resolve_wbs_id,//楼层
        }
      }).then((res) => {
        let resolveWbsId = res.data.resolve_wbs_id
        if (resolveWbsId) {
          let is_assembly = Number(res.data.is_assembly);
          let is_full_trim = Number(res.data.is_full_trim);
          this.requestParam = res.data;
          this.requestParam.is_assembly = is_assembly;
          this.requestParam.is_full_trim = is_full_trim;
          let name = res.data.assembly_rate_cal_file_name;
          let url = res.data.assembly_rate_cal_file;
          this.uploadDraweArr.push({ name: name, url: url });
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    handleRemove (file, fileList) {//删除
      console.log(file, fileList);
    },
    handlePreview (file) {//预览
      console.log(file);
    },
    handleExceed (files, fileList) {//上传文件个数的限制
      let selectFileNum = this.uploadDraweArr.length;//已选中的个数
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共有了 ${files.length + fileList.length + selectFileNum} 个文件`);
    },
    beforeRemove (file, fileList) {//删除前
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleClose (done) {
      this.$emit('update:objRow', {});//重置
      this.onCancel();
      this.dialogVisible = false;
      done()
    },
    onCancel () {//取消
      this.$refs.requestParam.resetFields();
      this.$emit('update:designInfoVisible', false);
    },
    editDesignInfoSave () {
      this.requestParam.resolve_wbs_id = this.objRow.resolve_wbs_id;
      console.log('uploadDraweArr=', this.uploadDraweArr)
      ProDesignDecomApi.editDesignInfo({
        data: this.requestParam
      }).then((res) => {
        if (res.code == 0) {
          this.nodeCount = this.$store.state.editDesignInfoCount;//项目设计与分解-左边树-编辑设计信息-确定的次数
          ++this.nodeCount;
          this.$store.dispatch('setEditDesignInfoCount', this.nodeCount)
          this.$message.success('操作成功')
          this.$emit('update:designInfoVisible', false);
          this.$emit('update:objRow', {})
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    onSure (data) {//确定
      this.$refs[data].validate((valid) => {
        if (valid) {
          this.editDesignInfoSave();//编辑设计信息
        } else {
          return false;
        }
      })
    },
    // 结构类型初始化标准码
    getStandardCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'construct_type'
        }
      }).then(res => {
        if (res.data) {
          this.structTypeArr = res.data.list;
          window.localStorage.setItem('constructTypeMap', JSON.stringify(this.structTypeArr))
        }
      },
        err => {
          console.log(err);
        }
      );
    },
    getStructCodeCommon () {//结构类型标准码
      let constructTypeMap = window.localStorage.getItem('constructTypeMap');
      if (constructTypeMap) {
        this.structTypeArr = JSON.parse(constructTypeMap);
      } else {
        this.getStandardCode();//标准码
      }
    }
  },
  watch: {//监听
    designInfoVisible (n, o) {
      if (this.designInfoVisible == true) {
        this.getStructCodeCommon();
        this.getDesignInfo();//编辑信息
      }
      this.getStandardCode();//结构类型标准码
      this.dialogVisible = n;
      console.log('w监听 objRow=', this.objRow, '$store.state.editDesignInfoCount=', this.$store.state.editDesignInfoCount)
    }
  },
  created () {
    if (this.designInfoVisible == true) {
      this.getStructCodeCommon();//结构类型标准码
      this.getDesignInfo();//编辑信息
      this.getBuildingTypeCode() //建筑类型标准码
    }
    this.dialogVisible = this.designInfoVisible;
    console.log('c监听 objRow=', this.objRow, '$store.state.editDesignInfoCount=', this.$store.state.editDesignInfoCount)
  }
}
</script>

<style lang="scss" scoped>
.add-version-container {
  .bottom-box {
    text-align: center;
    margin-top: 20px;
  }
  .common-style {
    width: 100% !important;
  }
}

.upload-quene-list {
  .upload-quene-item {
    width: 100%;
    height: 48px;
    border-bottom: 1px solid #e5e5e5;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding-left: 40px;
    font-size: 14px;
    color: #666;

    &:first-child {
      border-top: 1px solid #e5e5e5;
    }

    .file-name {
      width: 260px;
      margin-right: 120px;
      display: flex;
      align-items: center;
      img {
        width: 24px;
        height: 24px;
        margin-right: 15px;
      }
    }

    .file-size {
      width: 60px;
      margin-right: 40px;
    }

    .dir-name {
      width: 100px;
      margin-right: 40px;
      color: #1890ff;
    }

    .status {
      color: #333;
      display: flex;
      align-items: center;

      i {
        color: #52c41a;
        margin-right: 8px;
      }
    }
  }
}
.ul-style {
  margin-top: 20px;
  li {
    width: 100%;
    padding: 0px 10px 0px 0px;
    height: 36px;
    line-height: 36px;
    display: flex;
    flex-direction: row;
    justify-content: space-between !important;
    p {
      width: 60px;
      text-align: right;
    }
  }
  li:hover {
    // cursor: pointer;
    background-color: #eeeeee;
  }
  li p:nth-child(2) {
    span {
      cursor: pointer;
    }
  }
}
.ul-style li p:nth-child(1) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: calc(100% - 60px);
  display: flex;
}
</style>